<template>
  <view class="address-container">
    <view class="address-form">
      <view class="form-item">
        <text class="label">收货人</text>
        <input class="input" v-model="addressInfo.receiver" placeholder="请输入收货人姓名" />
      </view>
      
      <view class="form-item">
        <text class="label">手机号</text>
        <input class="input" v-model="addressInfo.phone" placeholder="请输入手机号" type="number" />
      </view>
      
      <view class="form-item">
        <text class="label">地区</text>
        <picker mode="region" :value="region" @change="onRegionChange">
          <view class="picker">{{ region.join(' ') || '请选择省市区' }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">详细地址</text>
        <textarea class="textarea" v-model="addressInfo.detail" placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息" />
      </view>
      
      <view class="form-item">
        <text class="label">默认地址</text>
        <switch :checked="addressInfo.isDefault" @change="onDefaultChange" />
      </view>
    </view>
    
    <view class="address-actions">
      <button class="btn save-btn" @tap="saveAddress">保存</button>
      <button class="btn delete-btn" v-if="mode === 'edit'" @tap="deleteAddress">删除</button>
    </view>
  </view>
</template>

<script>
import api from '@/utils/api.js';

export default {
  data() {
    return {
      mode: 'add', // add 或 edit
      addressId: '',
      region: [],
      addressInfo: {
        receiver: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        isDefault: false
      }
    };
  },
  onLoad(options) {
    this.mode = options.mode || 'add';
    this.addressId = options.id || '';
    
    if (this.mode === 'edit') {
      this.loadAddress();
    }
  },
  methods: {
    // 加载地址信息（编辑模式）
    loadAddress() {
      // 这里应该调用API获取地址详情，暂时使用模拟数据
      const mockAddress = {
        id: this.addressId,
        receiver: '张三',
        phone: '13800138000',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detail: '科技园南区',
        isDefault: true
      };
      
      this.addressInfo = { ...mockAddress };
      this.region = [mockAddress.province, mockAddress.city, mockAddress.district];
    },
    
    // 地区选择
    onRegionChange(e) {
      this.region = e.detail.value;
      this.addressInfo.province = this.region[0];
      this.addressInfo.city = this.region[1];
      this.addressInfo.district = this.region[2];
    },
    
    // 默认地址切换
    onDefaultChange(e) {
      this.addressInfo.isDefault = e.detail.value;
    },
    
    // 保存地址
    saveAddress() {
      if (!this.addressInfo.receiver) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        });
        return;
      }
      
      if (!this.addressInfo.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return;
      }
      
      // 验证手机号格式
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.addressInfo.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        });
        return;
      }
      
      if (!this.region.length) {
        uni.showToast({
          title: '请选择地区',
          icon: 'none'
        });
        return;
      }
      
      if (!this.addressInfo.detail) {
        uni.showToast({
          title: '请输入详细地址',
          icon: 'none'
        });
        return;
      }
      
      uni.showLoading({
        title: '保存中...'
      });
      
      // 调用API保存地址
      const savePromise = this.mode === 'add' 
        ? api.addAddress(this.addressInfo)
        : api.updateAddress(this.addressId, this.addressInfo);
      
      savePromise.then(res => {
        if (res.success) {
          uni.hideLoading();
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.hideLoading();
          uni.showToast({
            title: res.message || '保存失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('保存地址失败:', err);
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      });
    },
    
    // 删除地址
    deleteAddress() {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个地址吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '删除中...'
            });
            
            // 调用API删除地址
            api.deleteAddress(this.addressId).then(res => {
              if (res.success) {
                uni.hideLoading();
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                
                // 返回上一页
                setTimeout(() => {
                  uni.navigateBack();
                }, 1500);
              } else {
                uni.hideLoading();
                uni.showToast({
                  title: res.message || '删除失败',
                  icon: 'none'
                });
              }
            }).catch(err => {
              uni.hideLoading();
              console.error('删除地址失败:', err);
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss">
.address-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 150rpx;
}

.address-form {
  background-color: #fff;
  
  .form-item {
    display: flex;
    align-items: center;
    padding: 30rpx 40rpx;
    border-bottom: 1px solid #f0f0f0;
    
    .label {
      font-size: 28rpx;
      color: #333;
      width: 160rpx;
    }
    
    .input {
      font-size: 32rpx;
      color: #333;
      border: 1px solid #e0e0e0;
      border-radius: 8rpx;
      padding: 20rpx;
      background-color: #f9f9f9;
      flex: 1;
    }
    
    .picker {
      font-size: 32rpx;
      color: #333;
      border: 1px solid #e0e0e0;
      border-radius: 8rpx;
      padding: 20rpx;
      background-color: #f9f9f9;
      flex: 1;
    }
    
    .textarea {
      font-size: 32rpx;
      color: #333;
      border: 1px solid #e0e0e0;
      border-radius: 8rpx;
      padding: 20rpx;
      background-color: #f9f9f9;
      flex: 1;
      height: 200rpx;
    }
  }
}

.address-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 40rpx;
  display: flex;
  flex-direction: column;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .btn {
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    font-size: 32rpx;
    text-align: center;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &.save-btn {
      background-color: #ff9500;
      color: white;
    }
    
    &.delete-btn {
      background-color: #ff4d4f;
      color: white;
    }
  }
}
</style>